﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FormatUtil
{
    public class LogFileOpt
    {
        public FileStream fileStream { get; set; }
        public StreamWriter writer { get; set; }
        public string logFileName { get; set; }
        public string curDay { get; set; }
        public object lockLog { get; set; }
    }
    public class LogHelp
    {
        private static Dictionary<string, LogFileOpt> _logOptDic = new Dictionary<string, LogFileOpt>();
        private static object _lockObj = new object();

        #region 异常情况单独记录日志文件
        private static object elogobj = new object();
        private static FileStream efileStream;
        private static StreamWriter ewriter;
        private static string eLogFileName;
        private static string CurDay;
        #endregion







        public static void WriteLog(string msg, string sendOrRec, string deviceNo)
        {
            LogFileOpt logFileOpt = null;
            DateTime dateTime = DateTime.Now;
            lock (_lockObj)
            {

                if (_logOptDic.ContainsKey(deviceNo))
                {
                    logFileOpt = _logOptDic[deviceNo];
                }
            }
            if (logFileOpt == null)
            {
              

                logFileOpt = new LogFileOpt();
                logFileOpt.curDay = dateTime.ToString("dd");
                string filePath = Directory.GetCurrentDirectory() + "/logs";
                if (!System.IO.Directory.Exists(filePath))
                    System.IO.Directory.CreateDirectory(filePath);

                filePath = filePath + "/" + dateTime.ToString("yyyyMM") + "/" + deviceNo;
                if (!System.IO.Directory.Exists(filePath))
                    System.IO.Directory.CreateDirectory(filePath);
                logFileOpt.logFileName = filePath + "/" + dateTime.ToString("yyyy-MM-dd") + ".Log";

                logFileOpt.fileStream = new FileStream(logFileOpt.logFileName, FileMode.Append, FileAccess.Write, FileShare.Read);
                logFileOpt.writer = new StreamWriter(logFileOpt.fileStream, System.Text.Encoding.UTF8);

                lock (_lockObj)
                {
                    if (!_logOptDic.ContainsKey(deviceNo))
                    {
                        _logOptDic.Add(deviceNo, logFileOpt);
                    }
                }
            }
            else
            {
                if (logFileOpt.curDay != dateTime.ToString("dd"))
                {
                    logFileOpt.curDay = dateTime.ToString("dd");
                    string filePath = Directory.GetCurrentDirectory() + "/logs";
                    if (!System.IO.Directory.Exists(filePath))
                        System.IO.Directory.CreateDirectory(filePath);
                    filePath = filePath + "/" + dateTime.ToString("yyyyMM") + "/" + deviceNo;
                    if (!System.IO.Directory.Exists(filePath))
                        System.IO.Directory.CreateDirectory(filePath);
                    logFileOpt.logFileName = filePath + "/" + dateTime.ToString("yyyy-MM-dd") + ".Log";
                    logFileOpt.writer.Close();
                    logFileOpt.fileStream.Close();
                    logFileOpt.writer.Dispose();
                    logFileOpt.fileStream.Dispose();


                    logFileOpt.fileStream = new FileStream(logFileOpt.logFileName, FileMode.Append, FileAccess.Write, FileShare.Read);
                    logFileOpt.writer = new StreamWriter(logFileOpt.fileStream, System.Text.Encoding.UTF8);

                    lock (_lockObj)
                    {
                        if (_logOptDic.ContainsKey(deviceNo))
                        {
                            _logOptDic[deviceNo] = logFileOpt;
                        }
                    }

                }
            }

            if (logFileOpt.writer != null)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(sendOrRec);
                sb.Append("时间[").Append(dateTime.ToString("yyyy-MM-dd HH:mm:ss")).Append("] ");
                sb.Append(" ");
                sb.Append(msg);
                logFileOpt.writer.WriteLine(sb.ToString());
                logFileOpt.writer.Flush();
                sb.Clear();
                sb = null;
            }
            msg = null;
            deviceNo = null;
            sendOrRec = null;
            //}
        }


        #region 初始化异常程序日志
        public static void IniteLog()
        {
            lock (elogobj)
            {
                CurDay = DateTime.Now.ToString("yyyy-MM-dd");
                string efilePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/elogs";
                if (!System.IO.Directory.Exists(efilePath))
                    System.IO.Directory.CreateDirectory(efilePath);
                efilePath = efilePath + "/" + DateTime.Now.ToString("yyyyMM");
                if (!System.IO.Directory.Exists(efilePath))
                    System.IO.Directory.CreateDirectory(efilePath);
                eLogFileName = efilePath + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "_ex.Log";
                efileStream = new FileStream(eLogFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
                ewriter = new StreamWriter(efileStream, System.Text.Encoding.Default);
            }
        }
        #endregion

        #region 更换异常日志文件
        private static void ChangeeLogFile()
        {
            lock (elogobj)
            {
                string efilePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/elogs";
                if (!System.IO.Directory.Exists(efilePath))
                    System.IO.Directory.CreateDirectory(efilePath);
                efilePath = efilePath + "/" + DateTime.Now.ToString("yyyyMM");
                if (!System.IO.Directory.Exists(efilePath))
                    System.IO.Directory.CreateDirectory(efilePath);
                eLogFileName = efilePath + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "_ex.Log";
                ewriter.Close();
                efileStream.Close();
                efileStream = new FileStream(eLogFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
                ewriter = new StreamWriter(efileStream, System.Text.Encoding.Default);
            }
        }
        #endregion

        #region 写异常日志
        /// <summary>
        /// 写异常日志
        /// </summary>
        /// <param name="msg"></param>
        public static void WriteeLog(string Method, string msg)
        {
            string message = string.Format("Log:[Method:{0},message:{1}]", Method, msg);
            //Console.WriteLine(message);
            lock (elogobj)
            {
                try
                {
                    if (DateTime.Now.ToString("yyyy-MM-dd") != CurDay)
                    {
                        CurDay = DateTime.Now.ToString("yyyy-MM-dd");
                        ChangeeLogFile();
                    }
                    if (ewriter != null)
                    {
                        ewriter.BaseStream.Seek(0, SeekOrigin.End);
                        ewriter.WriteLine("{0} {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), message);
                        ewriter.Flush();
                    }
                }
                catch { }
            }
            msg = null;
            message = null;
         
          
        }
        #endregion

    }
}
